import React, {useState, useEffect} from 'react'
import { useNavigate } from 'react-router-dom'
import { message } from 'antd'
import validator from '@utils/validator'
import http from '@utils/http'

const SignIn = (props) => {
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const navigate = useNavigate();

  useEffect(() => {
  }, [])

  const handelLogin = async (e) => {
    const checkUsername = validator.username(username)
    const checkPassword = validator.password(password)

    if (!checkUsername.valid) {
      return message.error(checkUsername.message)
    }
    if (!checkPassword.valid) {
      return message.error(checkPassword.message)
    }

    http.post('login', {
      username,
      password
    }).then(res => {
      if (res.code !== 200) return message.error(res.message)
      localStorage.setItem('zg-jwt', res.data.token)
      message.success('登录成功')
      navigate('/')
    })
  }

  const goToSignUp = (e) => {
    e.preventDefault()
    navigate('/login/signUp')
  }

  const onKeyDown = (e) => {
    if (e.key === 'Enter') {
      handelLogin();
    }
  }

  return (
    <div className="login-main">
      <div className="login-content">
        <div className="content-item">
          <p className="content-item-title">欢迎回来！</p>
          <p className="content-item-subtitle">开始更快更好地管理你的资金</p>
        </div>
        <div className="content-form">
          <div className="content-form-item">
            <i className="form-item-icon user-icon"></i>
            <input className="form-input" value={username} onChange={(e) => setUsername(e.target.value)} type="text" placeholder="请输入账号" />
          </div>
          <div className="content-form-item">
            <i className="form-item-icon password-icon"></i>
            <input className="form-input" value={password} onKeyDown={onKeyDown} onChange={(e) => setPassword(e.target.value)} type="password" placeholder="请输入密码" />
          </div>
          <button className="login-btn" onClick={() => handelLogin()}>登录</button>
          <p className="form-footer">是否还未注册账号？<a href="#" onClick={goToSignUp}>点击注册</a></p>
        </div>
      </div>
    </div>
  )
}

export default SignIn;